package store.lunangangster.engine.bpmn.parser.handler;

import java.util.List;
import store.lunangangster.bpmn.model.Activity;
import store.lunangangster.bpmn.model.BoundaryEvent;
import store.lunangangster.bpmn.model.Event;
import store.lunangangster.bpmn.model.FlowElement;
import store.lunangangster.bpmn.model.Process;
import store.lunangangster.bpmn.model.definition.EventDefinition;
import store.lunangangster.bpmn.model.definition.MessageEventDefinition;
import store.lunangangster.engine.NodeFlowException;
import store.lunangangster.engine.bpmn.parser.BpmnParser;

public class BoundaryEventParseHandler extends EventParseHandler<BoundaryEvent> {

  @Override
  public void handle0(BpmnParser bpmnParser, BoundaryEvent boundaryEvent) {
    List<EventDefinition> eventDefinitions = boundaryEvent.getEventDefinitions();
    Process process = bpmnParser.getCurrentProcess();
    FlowElement flowElement = process.getFlowElements().get(boundaryEvent.getAttachedToRef());
    if (flowElement instanceof Activity) {
      Activity parentActivity = (Activity) flowElement;
      // two-way binding
      boundaryEvent.setAttachedActivity(parentActivity);
      parentActivity.addBoundaryEvent(boundaryEvent);
    } else {
      throw new NodeFlowException("\"attachedToRef\"属性应该指向一个Activity");
    }
    if (eventDefinitions == null || eventDefinitions.size() == 0) {
      return;
    }
    EventDefinition eventDefinition = eventDefinitions.get(0);
    // behavior的设置需要延迟到EventDefinition的解析
    if (eventDefinition instanceof MessageEventDefinition) {
      bpmnParser.getBpmnParseHandlers().handleElement(bpmnParser, eventDefinition);
    }
  }

  @Override
  public Class<? extends Event> getType() {
    return BoundaryEvent.class;
  }
}
